package com.zoweunion.mechanic.util;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletRequest;

public class Page {

	public static void main(String[] args) {
		System.out.println(appPage("5","3"));
	}

	public static Map<String, Object> appPage(String limit, String offset) {
		Map<String, Object> map = new HashMap<>();
		int nowPage = Integer.parseInt(offset);
		int pageSize = Integer.parseInt(limit);
		int currentPage = (nowPage - 1) * pageSize;
		map.put("limit", pageSize);
		map.put("offset", currentPage);
		return map;
	}

	public static Map<String,Object> getPageMap(HttpServletRequest request){
		Map<String,Object> map = new HashMap<String,Object>();
		int currentPage = 1;
		if (request.getParameter("page") != null
				&& request.getParameter("page") != "") {
			currentPage = Integer.valueOf(request.getParameter("page"))
					.intValue();
		}
		map.put("pageSize", request.getParameter("limit"));
		map.put("limit", (currentPage - 1) * Integer.parseInt(request.getParameter("limit")));
		map.put("currentPage", currentPage);
		return map;
	}

	public static List<Map<String, Object>> excutePage(List<Map<String, Object>> list,Map<String, Object> reqMap){

		//执行分页,若分页参数没传,则默认currentPage=1,pageSize=10
		Long currentPage = 1L;
		Long pageSize =10L;
		if (reqMap.containsKey("currentPage") && reqMap.get("currentPage").toString() != null && !"".equals(reqMap.get("currentPage").toString().trim())) {
			currentPage = Long.valueOf(reqMap.get("currentPage").toString());
		}
		if (reqMap.containsKey("pageSize") && reqMap.get("pageSize").toString() != null && !"".equals(reqMap.get("pageSize").toString().trim())) {
			pageSize = Long.valueOf(reqMap.get("pageSize").toString());
		}
		//执行分页逻辑
		List<Map<String, Object>> resultList = list.stream().skip((currentPage-1L)*pageSize).limit(pageSize).collect(Collectors.toCollection(ArrayList :: new));
		//返回结果
		return resultList;
		
	}

}
